<?php


namespace App\Libs\Contracts\Push\Vivo;


use App\Libs\Contracts\PayMent\Wxpay\WxPayApi;
use App\Libs\httpUtil;
use App\Models\User;

class VivoPushService
{
    private $appId = "19231";

    private $appKey = "3aa7cb16-3afb-4536-bbd4-222f25d07bdf";

    private $appSecret = "b2adfe40-f498-4839-8c50-84ba52b1f8de";

    public function push($title, $content, $userId)
    {
        $skipContent['type'] = 1;
        $http = new httpUtil();
        if ($userId) {
            $user = User::find($userId);
            if ($user['pushType'] == "VIVO") {
                if ($user['type'] == "ANDROID") {
                    \Log::info("VIVO推送");
                    $url = "https://api-push.vivo.com.cn/message/send";
                    $messageBody = [//15835621490981923125982
                        'regId' => $user['registrationId'],
                        'notifyType' => 1,
                        'title' => $title,
                        'content' => $content,
                        'skipType' => 1,
                       // 'skipContent' => json_encode($skipContent),
                        'requestId' => $this->getRequestId(),
                    ];
                    $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache", "authToken:" . $this->getAuthToken());
                    $result = $http->request($url, $messageBody, $headers, false);
                    \Log::info($result);
                    return true;
                }
            }
        } else {
            \Log::info("VIVO推送");
            $url = "https://api-push.vivo.com.cn/message/saveListPayload";
            $messageBody = [
                'notifyType' => 1,
                'title' => $title,
                'content' => $content,
                'skipType' => 1,
               // 'skipContent' => json_encode($skipContent),
                'requestId' => $this->getRequestId(),
            ];
            $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache", "authToken:" . $this->getAuthToken());
            $result = $http->request($url, $messageBody, $headers, false);
            \Log::info($result);
            return true;
        }
    }

    private function getRequestId()
    {
        $requestId = sprintf('%010d', time() - 946656000)
            . sprintf('%03d', (float)microtime() * 1000)
            . mt_rand(10, 99);

        return $requestId;
    }

    public function refreshAuthToken()
    {
        $data['appId'] = $this->appId;
        $data['appKey'] = $this->appKey;
        $data['timestamp'] = msectime();
        $http = new httpUtil();
        $messageBody = [
            'appId' => $data['appId'],
            'appKey' => $data['appKey'],
            'timestamp' => $data['timestamp'],
            'sign' => strtolower(md5($data['appId'] . $data['appKey'] . $data['timestamp'] . $this->appSecret))
        ];
        $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache",);
        $result = $http->request("https://api-push.vivo.com.cn/message/auth", $messageBody, $headers, false);
        if ($result['result'] == 0) {
            \RedisDB::setex(env("APP_NAME") . '-VIVO-authToken', 86400, $result['authToken']);
            return $result['authToken'];
        } else {
            \Log::error("获取Vivo authToken失败");
            \Log::error($result);
            return "";
        }


    }

    public function getAuthToken()
    {
        $authToken = \RedisDB::get(env("APP_NAME") . '-VIVO-authToken');
        if ($authToken) {
            return $authToken;
        } else {
            return $this->refreshAuthToken();
        }
    }

    /**
     * 生成签名
     * @param  $values
     * @return string
     */
    public function MakeSign($values, $key = '')
    {
        //签名步骤一：按字典序排序参数
        ksort($values);
        $string = $this->ToUrlParams($values);
        //签名步骤二：在string后加入KEY
        $string = $string . "&appSecret=" . $key;

        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为小写
        $result = strtolower($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($values)
    {
        $buff = "";
        foreach ($values as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
}